<?php

namespace app\admin\controller\trades\order;


use app\common\controller\Backend;
use app\admin\model\trades\assets\Order as oorder;
use app\admin\model\vactivities\Ticket;
use app\common\library\Iden;
use app\common\model\Push;
use Exception;
use think\Db;
use think\Request;
use app\admin\model\trades\order\Refund;
use app\admin\model\trades\order\Gainlog;
use app\admin\model\trades\order\Gain;

/**
 * 活动订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\trades\order\Order
     */
    protected $model = null;
    protected $account_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\trades\assets\Order;
        $this->account_model = new \app\admin\model\trades\assets\Myaccount;
        $this->view->assign('headList', $this->account_model->getHeadingList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $mywhere['account_id'] = $this->auth->id;
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                     ->where($where)
                    ->where($mywhere)
                    ->order($sort, $order)
                    ->paginate($limit);
            $amodel = new \app\admin\model\superdata\Account;
            $tmodel = new \app\admin\model\vactivities\Ticket;
            foreach ($list as $row) {
                $row->visible(['id','orderid','account_id','buyer_id','activity_id','amount','paytype','paytime','state','createTime','ordertype','name','ticket','num']);
                $row['amount'] = pricefentoyuan($row['amount']);
                $row['buyer_id'] = $amodel->getNameById($row['buyer_id']);

                $ticket = $tmodel->getTicketList($row['activity_id'],$row['ordertype'],$this->auth->id);
                $number = count($ticket);//数量
                if(empty($number)){
                    $row['num'] = 0;
                }else{
                    $row['num'] = $number;
                }

            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        $this->view->assign('now_function', 'trades/order/order/index');

        return $this->view->fetch();
    }


    /**
     * 详情
     */
    public function detail()
    {

        $ids = $this->request->param("ids");
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if(is_array($adminIds)){
            if (!in_array($row[$this->dataLimitField],$adminIds)){
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isAjax()) {
            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }

        $row = $row->toArray();
        $amodel = new \app\admin\model\superdata\Account;
        $actmodel = new \app\admin\model\vactivities\Activity;
        $serielmodel = new \app\admin\model\vactivities\Seriesactivity();
        $buyerId = $row['buyer_id'];
        $row['buyer_id'] = $amodel->getNameById($buyerId);
        $ordertype = $row['ordertype'];
        $row['ordertype'] = ($ordertype == oorder::ORDER_TYPE_1) ? '活动订单': '系列订单';
        $row['amount'] = pricefentoyuan($row['amount']);
        $row['paytype'] = ($row['paytype'] == 1) ? '支付宝':'微信';
        $row['paytime'] = date('Y-m-d H:i:s',$row['paytime']);
        $row['createTime'] = date('Y-m-d H:i:s',$row['createTime']);
        $activity_id = $row['activity_id'];
        $row['activity_id'] = $actmodel->getActNameById($activity_id);
        $row['state'] = isset($row['state']) ? oorder::PayState[$row['state']] :'';

        $row['buyerInfo'] = $amodel->getAccountInfo($buyerId);//买家信息

        if($ordertype == oorder::ORDER_TYPE_1){
            $row['activityInfo'] = $actmodel->getActivityInfo($activity_id);//活动信息
            if(!empty($row['activityInfo']['thumb'])){
                $row['thumbs'] = explode(',',$row['activityInfo']['thumb']);
            }else{
                $row['thumbs'] = [];
            }
        }
        if($ordertype == oorder::ORDER_TYPE_2){
            $row['activityInfo'] = $serielmodel->getSeriesInfo($activity_id);//系列活动信息
            if(!empty($row['activityInfo']['thumb'])){
                $row['thumbs'] = explode(',',$row['activityInfo']['thumb']);
            }else{
                $row['thumbs'] = [];
            }

        }

        $tmodel = new \app\admin\model\vactivities\Ticket;
        $tlist = $tmodel->getTicketList($activity_id,$ordertype,$this->auth->id);
        $row['tlist'] = isset($tlist) ? $tlist : '';
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

   /*
    * 退款页面
    * $ids 订单id
    */

   public function operate(){
       $ids = $this->request->param("ids");
       $row = $this->model->get(['id' => $ids]);
       if (!$row) {
           $this->error(__('No Results were found'));
       }
       $adminIds = $this->getDataLimitAdminIds();
       if(is_array($adminIds)){
           if (!in_array($row[$this->dataLimitField],$adminIds)){
               $this->error(__('You have no permission'));
           }
       }
       if ($this->request->isAjax()) {
           $this->success("Ajax请求成功", null, ['id' => $ids]);
       }
       $row = $row->toArray();
       $row['amount'] = pricefentoyuan($row['amount']);
       $this->view->assign("row", $row);
       return $this->view->fetch();
   }


   /*
    * 退款操作
    */
   public function refund(){
       $ids = $this->request->get('ids');
       $row = $this->model->get(['id' => $ids]);
       if (!$row) {
           $this->error(__('No Results were found'));
       }
       $row = $row->toArray();
       if($row['state'] != oorder::PAY_STATE_2){//判断订单是否已付款
           $this->error(__('此订单有误不能操作'));
       }

       $gmodel = new \app\admin\model\trades\order\Gain;
       $gain_info = $gmodel->getGainInfo($this->auth->id);
       if(($row['amount'] > $gain_info['total']) || ($row['amount'] > $gain_info['temp'])){//提现金额大于收益表的总收入或者 待确认金额
           $this->error(__('金额不足,无法提现！'));
       }

       Db::startTrans();
       try {
            $d['oid'] = $ids;
            $d['account_id'] = $row['buyer_id'];
            $d['ctime'] = time();
            $d['amount'] = $row['amount'];
            $d['finish_time'] = time();
            $d['state'] = Refund::REFUND_STATE_3;
            $d['operate_id'] = $this->auth->id;
            Db::name('activity_refund')->insert($d);//操作退款操作表
            Db::name('activity_order')->where('id', $ids)->update(['state' => oorder::PAY_STATE_4]);//订单表为已退款
            Db::name('activity_gain_log')->where('orderid', $row['orderid'])->update(['state' => Gainlog::GAINLOG_STATE_3]);//收益明细表置为已退款
            Db::name('activity_gain')->where('account_id', $this->auth->id)
                ->dec('total', $row['amount'])
                ->dec('temp', $row['amount'])
                ->update();//收益表减去退款金额
            Db::commit();
            $this->success("Ajax请求成功", null, ['id' => $ids]);
       } catch (Exception $e) {
           Db::rollback();
           $this->error($e->getMessage());
       }
   }

   /*
    * 获取优惠票的信息
    */
   public function getTicketInfo(){
       $oid = $this->request->get('oid');
       if(empty($oid)){
           return '';
       }
       $row = $this->model->get(['id' => $oid]);
       if (!$row) {
           return '';
       }
       $row = $row->toArray();



   }


}
